package com.sky.handler;

import com.alibaba.fastjson.JSON;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * @projectName: netty-cloud
 * @package: com.sky.handler
 * @className: AuthenticationSuccessHandler
 * @author: zhl
 * @description: 实现本方法，替换security登录成功后自动跳转页面的处理方式
 * @date: 2024/4/25 11:33
 * @version: 1.0
 */
public class MyAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    private RequestCache requestCache = new HttpSessionRequestCache();

    /**
     * Called when a user has been successfully authenticated.
     *
     * @param request        the request which caused the successful authentication
     * @param response       the response
     * @param authentication the <tt>Authentication</tt> object which was created during
     *                       the authentication process.
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        // 用户身份信息
        Object principal = authentication.getPrincipal();
        // 用户凭证
        Object credentials = authentication.getCredentials();
        // 用户权限信息
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        Map map = JSON.parseObject(JSON.toJSONString(principal), Map.class);
        System.out.println(map.toString());

        // 下面的代码逻辑来自 SavedRequestAwareAuthenticationSuccessHandler 类
        SavedRequest savedRequest = this.requestCache.getRequest(request, response);
        if (savedRequest == null) {
            super.onAuthenticationSuccess(request, response, authentication);
            return;
        }
        String targetUrlParameter = getTargetUrlParameter();
        if (isAlwaysUseDefaultTargetUrl()
                || (targetUrlParameter != null && StringUtils.hasText(request.getParameter(targetUrlParameter)))) {
            this.requestCache.removeRequest(request, response);
            super.onAuthenticationSuccess(request, response, authentication);
            return;
        }
        clearAuthenticationAttributes(request);
        // Use the DefaultSavedRequest URL
        String targetUrl = savedRequest.getRedirectUrl();

        if (StringUtils.hasText(targetUrl)) {
            // 跳转到登录之前的页面
            getRedirectStrategy().sendRedirect(request, response, targetUrl);
        } else {
            HashMap<String, Object> hashMap = new HashMap<>(16);
            hashMap.put("code", 200);
            hashMap.put("msg", "success");
            hashMap.put("data", principal);
            String json = JSON.toJSONString(hashMap);

            response.setContentType("application/json;charset=utf-8");
            response.getWriter().println(json);
        }
    }

    public void setRequestCache(RequestCache requestCache) {
        this.requestCache = requestCache;
    }
}
